<script setup lang="ts">
import { useGetDetail, useGetVerifyProgress, useUpdateRecord, useVerifyIdentity } from '@fl/api/elevator-api/verify'
import { treeFindLabel } from '@fl/utils/tree'

import { hasPermi } from '@fl/utils/has-permi'
import { cloneDeep } from 'lodash-es'
import { AUTH_RESULT, REPORT_IDENTITY_OPTIONS, VERIFY_STATUS } from '../constant'
import showMap from '../../history/components/map.vue'

const props = defineProps<{ data: any }>()
const visible = defineModel<boolean>('visible', { required: true })
const position = defineModel<any>('position', { required: true })

const form = reactive<any>({})
const formRef = ref()
const updateInfo = ref<any>()
const getVerifyProgressParams = computed(() => props.data?.id)
const { data: detailObj } = useGetDetail(getVerifyProgressParams)
const verifyStepData = computed(() => {
    if (verifyProgressData.value?.length) {
        const data = verifyProgressData.value.find((item: any) => !item.flag)
        if (data) {
            return data
        }
        else {
            return verifyProgressData.value.at(-2)
        }
    }
    return undefined
})
const activeIndex = computed(() => {
    if (verifyProgressData.value?.length) {
        const index = verifyProgressData.value.findIndex((item: any) => !item.flag)
        if (index !== -1) {
            return index
        }
        else {
            return verifyProgressData.value.length
        }
    }
    return 0
})

const { data: verifyProgressData, isLoading: isGetVerifyProgressLoading } = useGetVerifyProgress(getVerifyProgressParams)
const { isPending: isVerifyIdentityPending, mutate: verifyIdentity } = useVerifyIdentity()

const isSubmitLoading = computed(() => isVerifyIdentityPending.value)

const rules = {
    result: [
        {
            message: '请选择身份核实结果',
            required: true,
            trigger: 'change',
        },
    ],
}

const updateId = ref<string>('')
watch(visible, (val: any) => {
    if (val) {
        updateId.value = props.data?.id
    }
}, {
    immediate: true,
})
const { data: updateData } = useUpdateRecord(updateId)
watchEffect(() => {
    if (updateData.value) {
        updateInfo.value = cloneDeep(updateData.value[0])
        updateId.value = ''
    }
})

// #region UI Listener
async function onSubmitBtnClick() {
    try {
        await formRef.value.validate()
        const params = {
            id: props.data.id,
            info: {
                remark: form.remark,
            },
            result: form.result,
            status: props.data.status,
        }
        verifyIdentity(params, {
            onSuccess() {
                visible.value = false
                ElMessage.success('操作成功')
            },
        })
    }
    catch (error) {
        return error
    }
}

function onCancelBtnClick() {
    visible.value = false
}

function closed() {
    formRef.value?.resetFields()
    position.value = {
        longitude: null,
        latitude: null,
    }
}
// #endregion

// watchEffect(() => {
//     if (verifyStepData.value) {
//         const result: boolean | null = verifyStepData.value.result || undefined
//         const remark = verifyStepData.value.info?.remark || undefined
//         Object.assign(form, { remark, result })
//     }
// })

function getImageUrls(data: any) {
    const estateFileUrls = data?.estateFile ? data?.estateFile?.split(',') : []
    const houseFileUrls = data?.houseUrls ? data?.houseUrls?.split(',') : []
    return [...estateFileUrls, ...houseFileUrls]
}
</script>

<template>
    <el-drawer v-model="visible"
               :size="400"
               @closed="closed"
    >
        <template #header>
            <div class="bg-[#F2F3F5] text-[20px] font-semibold">
                {{ data?.status === VERIFY_STATUS.WAITING_FOR_VERIFY && data?.auth !== AUTH_RESULT.ERROR ? '核实结果' : '详情' }}
            </div>
        </template>

        <template #default>
            <el-skeleton v-if="isGetVerifyProgressLoading"
                         animated
            />

            <el-steps v-else-if="data?.auth !== AUTH_RESULT.ERROR"
                      :space="100"
                      :active="activeIndex"
                      finish-status="success"
            >
                <el-step v-for="item in verifyProgressData"
                         :key="item.name"
                >
                    <template #title>
                        <span class="text-[12px] text-[--el-color-primary]">{{ item.name || '结束' }}</span>
                    </template>
                </el-step>
            </el-steps>

            <el-form v-if="data?.status === VERIFY_STATUS.WAITING_FOR_VERIFY && data?.auth !== AUTH_RESULT.ERROR && hasPermi('身份失败-审核')"
                     ref="formRef"
                     :model="form"
                     :rules="rules"
                     class="mt-20"
            >
                <el-form-item label="身份核实结果"
                              prop="result"
                              class="font-semibold"
                >
                    <el-radio-group v-model="form.result">
                        <el-radio :value="true">
                            核实通过
                        </el-radio>

                        <el-radio :value="false">
                            核实不通过
                        </el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item prop="remark">
                    <el-input v-model="form.remark"
                              maxlength="200"
                              placeholder="请输入备注信息"
                              show-word-limit
                              type="textarea"
                    />
                </el-form-item>
            </el-form>

            <ul v-else-if="data?.auth !== AUTH_RESULT.ERROR && hasPermi('身份失败-详情')"
                class="mt-20 leading-24"
            >
                <li>操作人：{{ verifyStepData?.operaName }}</li>

                <li>操作时间：{{ verifyStepData?.finishTime }}</li>

                <li>身份核实结果：{{ verifyStepData?.result ? '核实通过' : '核实不通过' }}</li>

                <li>备注信息：{{ verifyStepData?.info?.remark }}</li>
            </ul>

            <el-divider v-if="data?.auth !== AUTH_RESULT.ERROR"
                        class="!mt-60"
            />

            <dl>
                <dt class="font-semibold leading-32">
                    上报人信息
                </dt>

                <dd class="leading-24">
                    账号：{{ detailObj?.applicantMobile }}
                </dd>

                <dd class="leading-24">
                    身份：{{ treeFindLabel({ targetValue: data?.reportIdentity, treeData: REPORT_IDENTITY_OPTIONS }) }}
                </dd>

                <dd class="leading-24">
                    联系方式：{{ detailObj?.reportMobile }}
                </dd>

                <dt class="font-semibold leading-32">
                    业主信息
                </dt>

                <dd class="leading-24">
                    姓名：{{ data?.ownerName }}
                </dd>

                <dd class="leading-24">
                    身份证号：{{ detailObj?.ownerIdCard }}
                </dd>

                <dt class="font-semibold leading-32">
                    房屋信息
                </dt>

                <dd class="leading-24 flex gap-8">
                    <span class="truncate w-[50%]">所在区：{{ data?.areaName }}</span>

                    <span class="truncate w-[50%]">街道：{{ data?.streetName }}</span>
                </dd>

                <dd class="leading-24 flex gap-8">
                    <span class="truncate w-[50%]">社区：{{ data?.communityName }}</span>

                    <span class="truncate w-[50%]">小区：{{ data?.projectName }}</span>
                </dd>

                <dd class="leading-24">
                    <span class="truncate w-[50%]">栋-单元：{{ `${data?.building}${data?.unit === '无' ? '' : `-${data?.unit}`}` }}</span>
                </dd>

                <dd class="leading-24">
                    <span class="truncate w-[50%]">自然栋编号：{{ data?.natureNo }}</span>
                </dd>

                <dd class="leading-24">
                    详细地址：{{ data?.houseAddr }}
                </dd>

                <dd class="leading-24">
                    不动产登记证号/房屋权属证明：{{ data?.estateNo }}
                </dd>

                <dd class="leading-24 flex gap-16">
                    <span class="truncate w-[fit-content]">其他证明材料</span>

                    <div class="pt-8 flex flex-1 flex-wrap gap-8">
                        <el-image v-for="item, index in getImageUrls(data)"
                                  :key="index"
                                  class="h-[80px] w-[80px]"
                                  :src="item"
                                  :preview-src-list="getImageUrls(data)"
                                  fit="fill"
                                  :initial-index="index"
                        />
                    </div>
                </dd>

                <div v-if="updateInfo?.changeList?.length > 0">
                    <dt class="font-semibold leading-32">
                        修改记录
                    </dt>

                    <div v-for="(item, index) in updateInfo.changeList"
                         :key="index"
                    >
                        <dd class="leading-24">
                            {{ item.label }}：{{ item.oldValue }} -> {{ item.newValue }}
                        </dd>
                    </div>

                    <dd class="leading-24">
                        修改人：{{ updateInfo?.createBy }}
                    </dd>

                    <dd class="leading-24">
                        <!-- 备注：{{ updateInfo?.remark || '' }} -->
                        备注：{{ updateInfo?.remark === 'null' ? '' : (updateInfo?.remark || '') }}
                    </dd>

                    <dd class="leading-24">
                        修改时间：{{ updateInfo?.createTime }}
                    </dd>
                </div>
            </dl>

            <!-- 地图 -->
            <div v-if="position?.longitude > 0"
                 class="abs"
            >
                <showMap v-model:longitude="position.longitude"
                         v-model:latitude="position.latitude"
                />
            </div>
        </template>

        <template #footer>
            <div v-if="data?.status === VERIFY_STATUS.WAITING_FOR_VERIFY && data?.auth !== AUTH_RESULT.ERROR && hasPermi('身份失败-审核')"
                 class="flex"
            >
                <el-button type="primary"
                           class="w-[50%]"
                           :loading="isSubmitLoading"
                           @click="onSubmitBtnClick"
                >
                    提交
                </el-button>

                <el-button class="w-[50%]"
                           @click="onCancelBtnClick"
                >
                    取消
                </el-button>
            </div>
        </template>
    </el-drawer>
</template>

<style scoped>
:deep(.el-step, .el-step.is-horizontal) {
    display: table !important;
}

:deep(.el-step__main) {
    display: table-caption;
    caption-side: top;
}

:deep(.el-step__head.is-success) {
    color: var(--el-color-primary);
    border-color: var(--el-color-primary);
}
.abs {
    position: fixed;
    top: 30px;
    right: 424px;
    background: #fff;
    width: calc(96vw - 600px);
    height: 92vh;
}
</style>
